import requests
import os
from plotly import offline
from operator import itemgetter

# 17.3 Hacker News API
# Y-Combinator Hacker News：https://news.ycombinator.com/
# 美国知名的孵化器YC做了一个黑客新闻的专栏，聚合了所有crypto圈的黑客攻击事件，阅读以提高防范意识。

# Make an API call, and store the response.
url = 'https://hacker-news.firebaseio.com/v0/topstories.json'
r = requests.get(url)
print(f"Status code: {r.status_code}")

# Process information about each submission.
submission_ids = r.json()
submission_dicts = []

for submission_id in submission_ids[:50]:
    # Make a separate API call for each submission.
    # 返回Hacker News上当前排名靠前的文章ID
    url = f"https://hacker-news.firebaseio.com/v0/item/{submission_id}.json"
    r = requests.get(url)
    print(f'id: {submission_id}\tstatus: {r.status_code}')
    response_dict = r.json()
    submission_dict = {
        'title': response_dict['title'],
        'hn_link': f"<a href='http://news.ycombinator.com/item?id={submission_id}'>{response_dict['title']}</a>",
        'score': response_dict['score'],
        'author': response_dict['by'],
    }
    submission_dicts.append(submission_dict)

submission_dicts = sorted(submission_dicts, key=itemgetter('score'), reverse=True)

titles, hn_links, scores = [], [], []
for submission_dict in submission_dicts[:10]:
    titles.append(f"{submission_dict['title']}<br />by {submission_dict['author']}")
    hn_links.append(submission_dict['hn_link'])
    scores.append(submission_dict['score'])


data = [{
    'type': 'bar',
    'x': hn_links,
    'y': scores,
    'hovertext': titles,
    'marker': {
        'color': 'rgb(60, 100, 150)',
        'line': {
            'width': 1.5,
            'color': 'rgb(25,25,25)'
        },
    },
    'opacity': 0.6,
}]

my_layout = {
    'title': 'Hacker News top stories',
    'titlefont': {
        'size': 28
    },
    'xaxis': {
        'title': 'Title',
        'titlefont': {
            'size': 24
        },
        'tickfont': {
            'size': 14
        },
    },
    'yaxis': {
        'title': 'Scores',
        'titlefont': {
            'size': 24
        },
        'tickfont': {
            'size': 14
        },
    },
}

fig = {'data': data, 'layout': my_layout}
if not os.path.exists('output'):
    os.mkdir('output')

offline.plot(fig, filename='output/HackerNewsTopStories.html')
